<template>
  <NavBar></NavBar>
  <div class="weight-container">
    <div class="weight-box">
      <div class="search-title">体重历史查询</div>
      <el-form :model="form" @submit.prevent="handleSearch">
        <el-form-item>
          <el-input
              v-model="form.searchParam"
              placeholder="输入牛耳标或牛ID..."
              style="max-width: 600px"
              class="input-with-select"
          >
            <template #append>
              <el-button type="primary" :icon="Search" native-type="submit" />
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <div v-loading="loading" class="chart-container">
        <div v-if="weightData.length > 0" ref="chartRef" style="height: 500px; margin-top: 20px;"></div>
        <el-empty v-else description="暂无体重数据"></el-empty>
      </div>

      <!-- 分页组件 -->
      <nav aria-label="..." class="pagination-container">
        <ul class="pagination">
          <li
              class="page-item"
              :class="{ disabled: currentPage === 1 }"
              @click="clickPage(-1)"
          >
            <a class="page-link" href="javascript:void(0)">上一页</a>
          </li>
          <li
              v-for="page in pages"
              :key="page"
              class="page-item"
              :class="{ active: page === currentPage }"
              @click="clickPage(page)"
          >
            <a class="page-link" href="javascript:void(0)">{{ page }}</a>
          </li>
          <li
              class="page-item"
              :class="{ disabled: currentPage === totalPages }"
              @click="clickPage(-2)"
          >
            <a class="page-link" href="javascript:void(0)">下一页</a>
          </li>
        </ul>
      </nav>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick, onBeforeUnmount, computed } from "vue";
import { useStore } from "vuex";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import * as echarts from 'echarts';
import NavBar from "@/components/NavBar.vue";
import { Search } from "@element-plus/icons-vue";

export default {
  components: { NavBar },
  setup() {
    const store = useStore();
    const route = useRoute();
    const form = reactive({ searchParam: "" });
    const weightData = ref([]);
    const currentCattle = ref(null);
    const loading = ref(false);
    const chartRef = ref(null);
    let chartInstance = null;

    // 分页相关状态
    const currentPage = ref(1);
    const pageSize = 8;
    const total = ref(0);
    const totalPages = computed(() => Math.ceil(total.value / pageSize));
    const pages = computed(() => {
      const start = Math.max(1, currentPage.value - 2);
      const end = Math.min(totalPages.value, currentPage.value + 2);
      return Array.from({ length: end - start + 1 }, (_, i) => start + i);
    });

    // 图表相关方法
    const resizeChart = () => {
      chartInstance?.resize();
    };

    const initChart = () => {
      if (!chartRef.value) return;
      chartInstance = echarts.init(chartRef.value);
      window.addEventListener('resize', resizeChart);
    };

    const updateChart = (data) => {
      if (!chartInstance) return;

      const option = {
        title: {
          text: '体重变化趋势',
          left: 'center',
          textStyle: { fontSize: 18, color: '#333' }
        },
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            const date = new Date(params[0].data.recordedAt);
            const diff = params[0].value - (currentCattle.value?.initialWeight || 0);
            return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}<br/>
                    体重：${params[0].value}kg<br/>
                    差值：${diff > 0 ? '+' : ''}${diff.toFixed(1)}kg`;
          }
        },
        xAxis: {
          type: 'category',
          data: data.map(item => {
            const date = new Date(item.recordedAt);
            return `${date.getMonth()+1}/${date.getDate()} ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`;
          }),
          axisLabel: { rotate: 45, margin: 15 },
          axisLine: { lineStyle: { color: '#666' } }
        },
        yAxis: {
          type: 'value',
          name: '体重 (kg)',
          min: value => Math.floor(value.min - 5),
          max: value => Math.ceil(value.max + 5),
          axisLine: { show: true, lineStyle: { color: '#666' } },
          splitLine: { lineStyle: { type: 'dashed' } }
        },
        series: [{
          data: data.map(item => ({
            value: item.weight,
            recordedAt: item.recordedAt
          })),
          type: 'bar',
          barWidth: '30%',
          itemStyle: {
            color: params => {
              const initial = currentCattle.value?.initialWeight || 0;
              if (params.value > initial + 5) return '#2ecc71'; // 增长良好
              if (params.value < initial - 5) return '#e74c3c'; // 体重下降
              return '#f1c40f'; // 维持稳定
            },
            borderRadius: [5, 5, 0, 0]
          },
          label: {
            show: true,
            position: 'top',
            formatter: '{c}kg',
            color: '#333',
            fontSize: 12
          }
        }],
        grid: {
          left: '5%',
          right: '5%',
          bottom: '20%',
          containLabel: true
        },
        animationDuration: 1000
      };

      chartInstance.clear();
      chartInstance.setOption(option, true);
    };

    // 获取数据方法
    const fetchWeightHistory = async (cattleId) => {
      loading.value = true;
      try {
        const resp = await store.dispatch("fetchWeightHistory", {
          cattleId,
          page: currentPage.value,
          pageSize: pageSize,
          token: store.state.user.token
        });

        if (resp.status === "success") {
          weightData.value = resp.data.data;
          total.value = resp.data.total;
          currentCattle.value = store.getters.getCattleById(cattleId);
          await nextTick();
          if (!chartInstance) initChart();
          updateChart(resp.data.data);
        }
      } catch (error) {
        ElMessage.error("获取体重数据失败");
      } finally {
        loading.value = false;
      }
    };

    // 分页点击处理
    const clickPage = (page) => {
      if (page === -1) page = currentPage.value - 1;
      else if (page === -2) page = currentPage.value + 1;

      if (page >= 1 && page <= totalPages.value) {
        currentPage.value = page;
        const cattleId = route.query.cattleId || form.searchParam;
        if (cattleId) fetchWeightHistory(cattleId);
      }
    };

    // 搜索处理
    const handleSearch = async () => {
      if (!form.searchParam) return;
      currentPage.value = 1;
      loading.value = true;
      const isEarTag = /^[a-zA-Z]/.test(form.searchParam);
      const isID = /^\d+$/.test(form.searchParam);

      try {
        if (isID) {
          await fetchWeightHistory(form.searchParam);
        } else if (isEarTag) {
          const cattle = await store.dispatch("fetchCattleByEarTag", {
            earTag: form.searchParam,
            token: store.state.user.token
          });
          if (cattle) await fetchWeightHistory(cattle.id);
        } else {
          ElMessage.error("输入的ID格式或耳标格式不正确");
        }
      } catch (error) {
        ElMessage.error("未找到相关牛只");
      } finally {
        loading.value = false;
      }
    };

    // 清理
    onBeforeUnmount(() => {
      if (chartInstance) {
        chartInstance.dispose();
        chartInstance = null;
      }
      window.removeEventListener('resize', resizeChart);
    });

    // 初始化
    onMounted(() => {
      const cattleId = route.query.cattleId;
      if (cattleId) {
        fetchWeightHistory(cattleId);
        form.searchParam = cattleId;
      }
    });

    return {
      form,
      weightData,
      currentCattle,
      loading,
      chartRef,
      currentPage,
      pages,
      totalPages,
      clickPage,
      handleSearch,
      Search
    };
  }
};
</script>
<style scoped>
/* 外层容器高度控制 */
.weight-container {
  display: flex;
  justify-content: center;
  padding: 20px 10px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 62px); /* 减去导航栏高度 */
  height: calc(100vh - 62px);     /* 固定高度保证滚动 */
  overflow-y: auto;               /* 启用垂直滚动 */
  box-sizing: border-box;
}

/* 主内容区调整 */
.weight-box {
  width: 80%;
  background-color: white;
  min-height: calc(100% - 40px); /* 动态高度 */
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  position: relative;
}

.search-title {
  text-align: center;
  font-size: 24px;
  margin-bottom: 20px;
  color: #409eff;
  font-weight: 600;
  flex-shrink: 0;
}

.el-form {
  flex-shrink: 0;
  margin-bottom: 20px;
}

/* 图表容器改造 */
.chart-container {
  flex: 1 1 auto;
  min-height: 400px;
  max-height: 60vh; /* 限制最大高度 */
  margin: 20px 0;
  padding: 15px;
  border-radius: 8px;
  background-color: #fff;
  overflow: hidden; /* 防止图表溢出 */
}

/* 图表实际绘制区域 */
.chart-container > div {
  width: 100% !important;
  height: 100% !important;
}

/* 分页组件固定定位 */
.pagination-container {
  position: sticky;
  bottom: 0;
  background: white;
  padding: 15px 0;
  margin-top: auto; /* 关键：自动顶部间距 */
  z-index: 2;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.pagination {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  margin: 0;
  padding: 0;
}

.page-item {
  cursor: pointer;
  user-select: none;
  list-style: none;
  margin: 2px;
}

.page-item.disabled .page-link {
  pointer-events: none;
  opacity: 0.6;
}

.page-item.active .page-link {
  background-color: #409eff;
  border-color: #409eff;
  color: white;
}

.page-link {
  display: block;
  color: #409eff;
  padding: 8px 16px;
  border: 1px solid #dee2e6;
  border-radius: 4px;
  text-decoration: none;
  transition: all 0.2s;
}

.page-link:hover {
  background-color: #f8f9fa;
  transform: translateY(-2px);
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .weight-box {
    width: 95%;
    padding: 15px;
  }

  .chart-container {
    max-height: 55vh;
  }
}

@media (max-width: 768px) {
  .weight-container {
    height: calc(100vh - 56px); /* 移动端导航栏可能更矮 */
  }

  .weight-box {
    width: 100%;
    border-radius: 0;
  }

  .chart-container {
    min-height: 300px;
    max-height: 50vh;
    padding: 10px;
  }
}

@media (max-width: 480px) {
  .weight-container {
    padding: 10px 5px;
    height: calc(100vh - 52px);
  }

  .chart-container {
    max-height: 45vh;
  }

  .search-title {
    font-size: 18px;
    margin-bottom: 15px;
  }

  .el-input {
    font-size: 14px;
  }
}
</style>